
import random


class _Pair(object):
	def __init__(self, w, it, *args, **kw):
		object.__init__(self)
		self.weight = w
		self.item = it

class WeightedList(object):

	def __init__(self, *args, **kw):
		object.__init__(self)
		self.list = []
		self.weight = 0

		for tup in args:
			self.add(*tup)

	def add(self, w, it):
		self.list.append(_Pair(w, it))
		self.weight += w

	def random(self):
		rval = random.randint(0, self.weight)
#
#		start the cumulative weight at zero
#
		cw = 0
		#print "rval = ", rval
		for pair in self.list:
#
#			add the weight for this element
#
			cw += pair.weight
			#print "	comparing ", cw
#
#			compare
#
			if rval <= cw:
				#print "	*** bingo!"
				return pair.item
		return None

if __name__ == "__main__":
	
	wlist = WeightedList(
		(1, "ten percent"),
		(3, "thirty percent"),
		(6, "sixty percent")
	)

	for n in range(20):
		s = wlist.random()
		if s == None:
			raise "Error!"
		print s

